#!user/bin/env python3
# -- coding: utf-8 --
# @Createtime：2023/6/17
# @Updatetime：15:23
# @Author：Test008
# @File：Higher-order_function.py
# @Description：Higher-order function
# print(abs(-10))
from datetime import datetime

x = abs(-2)


# print(x)
def add(a, b, f):
    return f(a) + f(b)


# print(add(-5, 6, abs))
# 比如我们有一个函数f(x)=x2，要把这个函数作用在一个list [1, 2, 3, 4, 5, 6, 7, 8, 9]上，就可以用map()实现如下：
def f(x):
    return x * x


r = map(f, [i for i in range(10)])
# print(list(r))
# 把这个list所有数字转为字符串：
R = (map(str, [i for i in range(10)]))
# print(list(R))
# print(sum([i for i in range(5)]))

from functools import reduce


def add(x, y):
    return x * y


Re = reduce(add, [i for i in range(1, 5)])
from functools import reduce


# print(Re)
# 如果考虑到字符串str也是一个序列，对上面的例子稍加改动，配合map()，我们就可以写出把str转换为int的函数：
def str2int(s):
    def fn(x, y):
        return x * 10 + y

    # Re1 = reduce(fn, [i for i in range(5)])
    # print(Re1)
    def chart2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]

    return reduce(fn, map(chart2num, s))


s = str2int('13579')
# print(s)
A = ['adam', 'LISA', 'barT']


def cap(c):
    return c.capitalize()


L1 = list(map(cap, A))


# print(L1)
# Python内建的filter()函数用于过滤序列
def is_odd(n):
    return n % 2 == 1


Odd = list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8]))


# print(Odd)

def not_empty(s):
    return s and s.strip()


NotEmpty = list(filter(not_empty, ['A', '', 'B', 'None', 'C']))


# print(NotEmpty)

def _odd_iter():
    n = 1
    while True:
        n = n + 1
        yield n


def _not_divisible(n):
    return lambda x: x % n > 0


def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_divisible, it)


# for n in primes():
#     if n<100:
#         print(n)
#     else:
#         break

# 排序算法
# print(sorted([36,5,-12,9,-21]))
# print(sorted([36,5,-12,9,-21], key=abs))
name = ['bob', 'about', 'Zoo', 'Credit']


# print(sorted(name))
# print(sorted(name, key=str.lower))
# print(sorted(name, key=str.lower, reverse=True))
# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# 根据姓名排序
# print(sorted(L))
def by_name(t):
    return t[0].lower()


L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
L1 = sorted(L, key=by_name)


# print(L1)

def by_sort(t):
    return t[1]


L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
L1 = sorted(L, key=by_sort, reverse=True)


# print(L1)
# 闭包
def outer(a):
    b = 10

    def inner():
        print(a + b)

    return inner()


# if __name__ == '__main__':
#     demo = outer(5)
# 匿名函数
la = [1, 2, 3, 4, 5, 6, 7]
Lam = list(map(lambda x: x ** 2, la))
# print(Lam)

f = lambda x: x * 5 - 1


# print(f(2))
# 装饰器
def now():
    print(datetime.now())


f = now


# print(f.__name__)

def log(func):
    def wrapper(*args, **kwargs):
        print('run %s():' % func.__name__)
        return func(*args, **kwargs)

    return wrapper


log(now)
